from domain.domain import File
from service.Message import Message, CodeMessageData
import re


class FileDAO():
    def __init__(self):
        print("FileDAO init")

    def add(self, session, oneFile):
        """
        :param session: session
        :param oneFile: one File data
        :return: Message Object
        """
        data = []
        try:
            session.add(oneFile)
            code = 0000
            session.commit()
        except Exception as ex:
            exStr = str(ex)
            exArr = re.search("\([0-9]{4}.*\)", exStr)
            print(exArr[0])
            exTwo = exArr[0].replace("(", "").split(',')[0]
            code = int(exTwo)
            session.rollback()
        if (code not in CodeMessageData):
            code = 2001
        return Message(code, CodeMessageData[code])

    def deleteById(self, session, id):
        """
        :param session: session
        :param id: personalTeamid
        :return: result Message Object
        """
        data = []
        try:
            session.query(File).filter(File.id == id).delete()
            code = 0000
            session.commit()
        except Exception as ex:
            exStr = str(ex)
            exArr = re.search("\([0-9]{4}.*\)", exStr)
            print(exArr[0])
            exTwo = exArr[0].replace("(", "").split(',')[0]
            code = int(exTwo)
            session.rollback()
        if (code not in CodeMessageData):
            code = 2001
        return Message(code, CodeMessageData[code])

    def update(self, session, oneData):
        """
        :param session: sql session
        :param oneData: one file data
        :return:
        """
        code = 0000
        try:
            result = session.query(File).filter(File.type_file_id == oneData.type_file_id).one()
            # 这里只有下面两个数据可变
            result.year = oneData.year
            result.file_name = oneData.file_name
            session.commit()
        except:
            code = 1039
            session.rollback()
        if (code not in CodeMessageData):
            code = 2001
        return Message(code, CodeMessageData[code])

    def getInfoByTypeFileId(self, session, typeFileId):
        code = 0000
        data = []
        try:
            result = session.query(File).filter(File.type_file_id == typeFileId).one()
            data.append(result)
        except:
            code = 1051
            data = []
        return Message(code, CodeMessageData[code], data)
